package com.cc.pms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.pms.mapper.TagMapper;
import com.cc.common.core.domain.R;
import com.cc.common.utils.SecurityUtils;
import com.cc.pms.domain.UserTag;
import com.cc.pms.domain.vo.TagVo;
import com.cc.pms.mapper.UserTagMapper;
import com.cc.pms.service.IUserTagService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 关联用户与标签，记录用户选择的标签 服务实现类
 * </p>
 *
 * @author corleone
 * @since 2025-04-19
 */
@Service
public class UserTagServiceImpl extends ServiceImpl<UserTagMapper, UserTag> implements IUserTagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public void removeByTagIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return;
        }
        lambdaUpdate().in(UserTag::getTagId, Arrays.stream(ids).toArray()).remove();
    }

    @Override
    public R<Boolean> updateUserTagByUserId(Long userId , Long[] tagIds) {
        removeTagByUserId(userId);
        if (tagIds == null || tagIds.length == 0) {
            return R.ok();
        }
        List<UserTag> userTagList = Arrays.stream(tagIds).map(tagId -> {
            UserTag userTag = new UserTag();
            userTag.setTagId(tagId);
            userTag.setUserId(userId);
            return userTag;
        }).collect(Collectors.toList());
        return R.ok(saveBatch(userTagList));
    }

    @Override
    public List<UserTag> queryTagByUserId(Long userId) {
        return lambdaQuery().eq(UserTag::getUserId, userId).list();
    }

    @Override
    public List<TagVo> queryUserTag() {
        return tagMapper.queryUserTag(SecurityUtils.getUserId());
    }

    private void removeTagByUserId(Long userId) {
        lambdaUpdate().eq(UserTag::getUserId, userId).remove();
    }

}
